import EventHub from '/utils/event-emitter'

Page({
  data: {
    str: ''
  },
  onLoad(query) {
    EventHub.addEventListener('navigateBackToMiniprogram', (payload) => {
      // 根据插件返回的数据，更新当前页面
      this.setData({
        str: JSON.stringify(payload)
      })

      // 跳转到当前页面。根据getCurrentPages计算出插件页面有多少个
      const delta = this.getDeltaFromCurrengPages()
      if (delta > 0) {
        my.navigateBack({
          delta
        });
      }
    })
  },
  getDeltaFromCurrengPages() {
    const currentPages = getCurrentPages();
    const len = currentPages.length;
    let delta = 0;
    for (let i = len - 1; i >= 0; i--) {
      if (currentPages[i] !== null) {
        break;
      } else {
        delta = delta + 1;
      }
    }
    return delta;
  },
  navigateToPlugin() {
    my.navigateTo({
      url: 'plugin://myPlugin/index-page',
    });
  }
});
